mod obstacle;
mod player;
mod sound;
mod collectible;
mod boomball;
use boomball::{BoomBall, LiveBall};

use bracket_lib::prelude::*;
use image::*;
use obstacle::Obstacle;
use player::Player;
use collectible::Collectible;

use sound::{start_sound_thread, SoundEffect};
use std::sync::mpsc::{self, Sender};
use std::fs::{File, OpenOptions};
use std::io::{Read, Write};

// 按钮动作枚举
#[derive(Clone, Copy)]
enum ButtonAction {
    Play,
    Quit,
    ToggleAudio,
    ToggleMusic,
    Restart,
    ShowRecord, // 新增
    EasyMode, // 新增
    ChallengeMode, // 新增
    ReturnMenu, // 新增
}

// 按钮结构体
struct Button {
    x: i32,
    y: i32,
    width: i32,
    height: i32,
    text: String,
    action: ButtonAction,
    hover: bool,
}

impl Button {
    fn new(x: i32, y: i32, width: i32, height: i32, text: String, action: ButtonAction) -> Self {
        Button {
            x,
            y,
            width,
            height,
            text,
            action,
            hover: false,
        }
    }

    fn render(&self, ctx: &mut BTerm) {
        let bg_color = if self.hover { YELLOW } else { WHITE };
        let fg_color = if self.hover { BLACK } else { BLACK };
        
        // 绘制按钮背景
        for dx in 0..self.width {
            for dy in 0..self.height {
                ctx.set_bg(self.x + dx, self.y + dy, bg_color);
                ctx.set(self.x + dx, self.y + dy, fg_color, bg_color, to_cp437(' '));
            }
        }
        
        // 绘制按钮边框
        for dx in 0..self.width {
            ctx.set(self.x + dx, self.y, BLACK, bg_color, to_cp437('─'));
            ctx.set(self.x + dx, self.y + self.height - 1, BLACK, bg_color, to_cp437('─'));
        }
        for dy in 0..self.height {
            ctx.set(self.x, self.y + dy, BLACK, bg_color, to_cp437('│'));
            ctx.set(self.x + self.width - 1, self.y + dy, BLACK, bg_color, to_cp437('│'));
        }
        
        // 绘制按钮文字
        let text_x = self.x + (self.width - self.text.len() as i32) / 2;
        let text_y = self.y + self.height / 2;
        ctx.print(text_x, text_y, &self.text);
    }

    fn contains_point(&self, x: i32, y: i32) -> bool {
        x >= self.x && x < self.x + self.width && y >= self.y && y < self.y + self.height
    }
}

enum GameMode {
    Menu,
    Playing,
    Paused,   
    End,
}

/// 游戏屏幕宽度
const SCREEN_WIDTH: i32 = 120;
/// 游戏屏幕高度
const SCREEN_HEIGHT: i32 = 80;
/// 每隔75毫秒做一些事情
const FRAME_DURATION: f32 = 75.0;
/// 初始障碍物数量
const INITIAL_OBSTACLES: usize = 3;
/// 障碍物间隔
const OBSTACLE_INTERVAL: i32 = 50;



struct State {
    player: Player,
    frame_time: f32,
    mode: GameMode,
    obstacles: Vec<Obstacle>,
    collectibles: Vec<Collectible>, // 小球列表
    score: i32, // 分数
    record: i32, // 最高分
    sound_tx: Sender<SoundEffect>,
    audio_enabled: bool, // 音效开关
    music_enabled: bool, // 音乐开关
    music_ctrl_tx: Sender<bool>, // 控制音乐线程
    buttons: Vec<Button>, // 按钮列表
    last_obstacle_gap_y: Option<i32>, // 最后一个障碍物的中心点位置
    game_speed: f32, // 游戏速度，影响障碍物移动
    last_speed_increase_score: i32, // 上次加速时的分数
    showing_record: bool, // 是否显示最高分弹窗
    record_popup_just_opened: bool, // 弹窗刚打开时忽略第一次点击
    lives: i32, // 剩余生命数
    is_easy_mode: bool, // 是否为简单模式
    respawn_timer: Option<f32>, // 撞击后重生倒计时（毫秒）
    pending_skip_obstacle: Option<usize>, // 需要跳过的障碍物索引
    is_challenge_mode: bool, // 是否为挑战模式
    boom_balls: Vec<BoomBall>, // 屏幕上的boom小球
    live_balls: Vec<LiveBall>, // 屏幕上的live小球
    record_easy: i32,
    record_normal: i32,
    record_challenge: i32,
}

impl State {
    fn new() -> Self {
        let sound_tx = start_sound_thread();

        // 背景音乐线程
        let (music_ctrl_tx, music_ctrl_rx) = mpsc::channel();
        std::thread::spawn(move || {
            use rodio::{Decoder, OutputStream, Sink, Source};
            use std::fs::File;
            use std::io::BufReader;
            
            println!("背景音乐线程启动");
            
            let (_stream, stream_handle) = match OutputStream::try_default() {
                Ok(stream) => {
                    println!("音频输出流初始化成功");
                    stream
                },
                Err(e) => {
                    println!("音频输出流初始化失败: {}", e);
                    return;
                }
            };
            
            let file = match File::open("assets/background.wav") {
                Ok(f) => {
                    println!("成功打开background.wav文件");
                    f
                },
                Err(e) => {
                    println!("无法打开background.wav文件: {}", e);
                    return;
                }
            };
            
            let source = match Decoder::new(BufReader::new(file)) {
                Ok(s) => {
                    println!("成功解码音频文件");
                    s.repeat_infinite()
                },
                Err(e) => {
                    println!("音频解码失败: {}", e);
                    return;
                }
            };
            
            let sink = match Sink::try_new(&stream_handle) {
                Ok(s) => {
                    println!("成功创建音频播放器");
                    s
                },
                Err(e) => {
                    println!("创建音频播放器失败: {}", e);
                    return;
                }
            };
            
            sink.append(source);
            sink.pause(); // 默认暂停
            println!("背景音乐线程准备就绪，等待播放指令");
            
            loop {
                if let Ok(enable) = music_ctrl_rx.recv() {
                    if enable {
                        println!("收到播放指令，开始播放音乐");
                        sink.play();
                    } else {
                        println!("收到暂停指令，暂停音乐");
                        sink.pause();
                    }
                }
            }
        });

        let mut obstacles = Vec::new();
        let mut collectibles = Vec::new();
        let mut x = SCREEN_WIDTH;
        for _ in 0..INITIAL_OBSTACLES {
            let obstacle = Obstacle::new(x, 0);
            // 为每个障碍物生成小球
            let mut random = RandomNumberGenerator::new();
            let collectible_count = random.range(0, 3);
            for _ in 0..collectible_count {
                let collectible_x = x + random.range(5, OBSTACLE_INTERVAL - 5);
                let collectible_y = random.range(5, SCREEN_HEIGHT - 5);
                collectibles.push(Collectible::new(collectible_x, collectible_y));
            }
            obstacles.push(obstacle);
            x += OBSTACLE_INTERVAL;
        }
        
        // 读取最高分
        let mut record = 0;
        if let Ok(mut file) = File::open("record.txt") {
            let mut buf = String::new();
            if file.read_to_string(&mut buf).is_ok() {
                if let Ok(val) = buf.trim().parse::<i32>() {
                    record = val;
                }
            }
        }

        // 读取3个模式的最高分
        let record_easy = std::fs::read_to_string("record_easy.txt").ok().and_then(|s| s.trim().parse().ok()).unwrap_or(0);
        let record_normal = std::fs::read_to_string("record_normal.txt").ok().and_then(|s| s.trim().parse().ok()).unwrap_or(0);
        let record_challenge = std::fs::read_to_string("record_challenge.txt").ok().and_then(|s| s.trim().parse().ok()).unwrap_or(0);

        let state = State {
            player: Player::new(5, 25),
            frame_time: 0.0,
            mode: GameMode::Menu,
            obstacles,
            collectibles,
            score: 0,
            record, // 初始化最高分
            sound_tx,
            audio_enabled: true,
            music_enabled: true,
            music_ctrl_tx: music_ctrl_tx.clone(),
            buttons: Vec::new(),
            last_obstacle_gap_y: None,
            game_speed: 1.0, // 初始速度
            last_speed_increase_score: 0, // 上次加速时的分数
            showing_record: false,
            record_popup_just_opened: false,
            lives: 1,
            is_easy_mode: false,
            respawn_timer: None,
            pending_skip_obstacle: None,
            is_challenge_mode: false,
            boom_balls: Vec::new(),
            live_balls: Vec::new(),
            record_easy,
            record_normal,
            record_challenge,
        };
        
        // 如果音乐默认开启，立即发送播放指令
        let _ = music_ctrl_tx.send(true);
        
        state
    }

    // 播放音效的辅助函数
    fn play_sound(&self, effect: SoundEffect) {
        if self.audio_enabled {
            let _ = self.sound_tx.send(effect);
        }
    }

    // 控制背景音乐的辅助函数
    fn set_music(&self, enable: bool) {
        let _ = self.music_ctrl_tx.send(enable);
    }

    // 创建受限制的障碍物
    fn create_obstacle_with_constraint(&mut self, x: i32, _score: i32) -> Obstacle {
        let mut random = RandomNumberGenerator::new();
        let size = random.range(10, (SCREEN_HEIGHT * 2) / 3); // 可通过范围最小10，最大2/3屏幕宽度
        let half_size = size / 2;
        let min_gap_y = half_size + 5;
        let max_gap_y = SCREEN_HEIGHT - half_size - 5;
        let gap_y = if let Some(last_gap_y) = self.last_obstacle_gap_y {
            // 限制与上一个障碍物的差距不超过2/3屏幕高度
            let max_diff = (SCREEN_HEIGHT * 2) / 3;
            let min_allowed = i32::max(min_gap_y, last_gap_y - max_diff);
            let max_allowed = i32::min(max_gap_y, last_gap_y + max_diff);
            if min_allowed < max_allowed {
                random.range(min_allowed, max_allowed)
            } else {
                min_gap_y
            }
        } else {
            // 第一个障碍物，随机生成
            if min_gap_y < max_gap_y {
                random.range(min_gap_y, max_gap_y)
            } else {
                min_gap_y
            }
        };
        self.last_obstacle_gap_y = Some(gap_y);
        let mut random = RandomNumberGenerator::new();
        Obstacle {
            x,
            gap_y,
            size,
            img: image::open("assets/obstacle.png").unwrap(),
            shape_type: random.range(0, 4), // 随机形状类型
            shape_factor: random.range(50, 150) as f32 / 100.0, // 随机形状因子 0.5-1.5
        }
    }

    // 生成小球
    fn generate_collectibles(&mut self, obstacle_x: i32, obstacle_gap_y: i32, obstacle_size: i32) {
        let mut random = RandomNumberGenerator::new();
        // 决定生成0-2个小球
        let collectible_count = random.range(0, 3);
        if collectible_count == 0 {
            return;
        }
        let half_size = obstacle_size / 2;
        // 小球出现的竖直范围：障碍物范围上下各扩大10单位
        let min_y = i32::max(0, obstacle_gap_y - half_size - 10);
        let max_y = i32::min(SCREEN_HEIGHT - 6, obstacle_gap_y + half_size + 10);
        if min_y >= max_y {
            return;
        }
        let mut used_x_positions = Vec::new();
        for _ in 0..collectible_count {
            // 生成x坐标，确保不与之前的小球在同一列
            let min_x = obstacle_x + 10;
            let max_x = obstacle_x + OBSTACLE_INTERVAL - 10;
            if min_x >= max_x {
                continue;
            }
            let mut collectible_x = random.range(min_x, max_x);
            while used_x_positions.contains(&collectible_x) {
                collectible_x = random.range(min_x, max_x);
            }
            used_x_positions.push(collectible_x);
            // 生成y坐标，限制相邻小球的竖直高度差
            let collectible_y = if let Some(last_collectible) = self.collectibles.last() {
                let max_diff = SCREEN_HEIGHT / 3;
                let min_allowed = i32::max(min_y, last_collectible.y - max_diff);
                let max_allowed = i32::min(max_y, last_collectible.y + max_diff);
                if min_allowed < max_allowed {
                    random.range(min_allowed, max_allowed)
                } else {
                    min_y
                }
            } else {
                random.range(min_y, max_y)
            };
            self.collectibles.push(Collectible::new(collectible_x, collectible_y));
        }
    }

    // 生成boom小球
    fn try_generate_boom(&mut self, obstacle_x: i32, gap_y: i32, size: i32) {
        if !self.is_challenge_mode { return; }
        if !self.boom_balls.is_empty() { return; }
        let mut rng = RandomNumberGenerator::new();
        if rng.range(0, 100) < 30 { // 30%概率生成
            // 竖直范围与障碍物gap一致，横向远离gap 5像素
            let min_y = gap_y - size/2 + 5;
            let max_y = gap_y + size/2 - 5;
            if min_y < max_y {
                let boom_y = rng.range(min_y, max_y);
                let boom_x = obstacle_x + rng.range(10, OBSTACLE_INTERVAL - 10);
                self.boom_balls.push(BoomBall::new(boom_x, boom_y));
            }
        }
    }

    fn try_generate_live_ball(&mut self, obstacle_x: i32, gap_y: i32, size: i32) {
        if !self.is_challenge_mode { return; }
        if !self.live_balls.is_empty() { return; }
        let mut rng = RandomNumberGenerator::new();
        if rng.range(0, 100) < 30 { // 30%概率生成
            let min_y = gap_y - size/2 + 5;
            let max_y = gap_y + size/2 - 5;
            if min_y < max_y {
                let live_y = rng.range(min_y, max_y);
                let live_x = obstacle_x + rng.range(10, OBSTACLE_INTERVAL - 10);
                self.live_balls.push(LiveBall::new(live_x, live_y));
            }
        }
    }

    // 创建主菜单按钮
    fn create_menu_buttons(&mut self) {
        self.buttons.clear();
        self.buttons.push(Button::new(25, 7, 30, 5, "Easy Mode".to_string(), ButtonAction::EasyMode));
        self.buttons.push(Button::new(25, 13, 30, 5, "Challenge Mode".to_string(), ButtonAction::ChallengeMode));
        self.buttons.push(Button::new(25, 19, 30, 5, "Normal Mode".to_string(), ButtonAction::Play));
        self.buttons.push(Button::new(25, 25, 30, 5, "View Record".to_string(), ButtonAction::ShowRecord));
        self.buttons.push(Button::new(25, 31, 30, 5, "Quit Game".to_string(), ButtonAction::Quit));
        self.buttons.push(Button::new(25, 37, 30, 5, format!("Audio: {}", if self.audio_enabled { "ON" } else { "OFF" }), ButtonAction::ToggleAudio));
        self.buttons.push(Button::new(25, 43, 30, 5, format!("Music: {}", if self.music_enabled { "ON" } else { "OFF" }), ButtonAction::ToggleMusic));
    }

    // 创建游戏结束按钮
    fn create_end_buttons(&mut self) {
        self.buttons.clear();
        self.buttons.push(Button::new(25, 25, 30, 5, "Play Again".to_string(), ButtonAction::Restart));
        self.buttons.push(Button::new(25, 32, 30, 5, "Return to Menu".to_string(), ButtonAction::ReturnMenu));
        self.buttons.push(Button::new(25, 39, 30, 5, "Quit Game".to_string(), ButtonAction::Quit));
        self.buttons.push(Button::new(25, 46, 30, 5, format!("Audio: {}", if self.audio_enabled { "ON" } else { "OFF" }), ButtonAction::ToggleAudio));
        self.buttons.push(Button::new(25, 53, 30, 5, format!("Music: {}", if self.music_enabled { "ON" } else { "OFF" }), ButtonAction::ToggleMusic));
    }

    // 处理按钮点击，返回是否处理了点击
    fn handle_button_click(&mut self, action: ButtonAction, ctx: &mut BTerm) -> bool {
        match action {
            ButtonAction::EasyMode => {
                self.is_easy_mode = true;
                self.lives = 3;
                self.restart();
                true
            },
            ButtonAction::ChallengeMode => {
                self.is_challenge_mode = true;
                self.is_easy_mode = false;
                self.lives = 3;
                self.restart();
                true
            },
            ButtonAction::Play => {
                self.is_easy_mode = false;
                self.lives = 1;
                self.restart();
                true
            },
            ButtonAction::ShowRecord => {
                self.showing_record = true;
                self.record_popup_just_opened = true;
                true
            },
            ButtonAction::Quit => {
                ctx.quitting = true;
                true
            },
            ButtonAction::ToggleAudio => {
                self.audio_enabled = !self.audio_enabled;
                // 重新创建按钮以更新文本
                match self.mode {
                    GameMode::Menu => self.create_menu_buttons(),
                    GameMode::End => self.create_end_buttons(),
                    _ => {}
                }
                true
            },
            ButtonAction::ToggleMusic => {
                self.music_enabled = !self.music_enabled;
                self.set_music(self.music_enabled);
                // 重新创建按钮以更新文本
                match self.mode {
                    GameMode::Menu => self.create_menu_buttons(),
                    GameMode::End => self.create_end_buttons(),
                    _ => {}
                }
                true
            },
            ButtonAction::Restart => {
                self.restart();
                true
            },
            ButtonAction::ReturnMenu => {
                self.mode = GameMode::Menu;
                self.buttons.clear();
                true
            },
            _ => false
        }
    }

    // 处理鼠标事件
    fn handle_mouse(&mut self, ctx: &mut BTerm) -> bool {
        let (mouse_x, mouse_y) = ctx.mouse_pos();
        
        // 重置所有按钮的悬停状态
        for button in &mut self.buttons {
            button.hover = button.contains_point(mouse_x, mouse_y);
        }
        
        // 检查鼠标点击
        if ctx.left_click {
            for button in &self.buttons {
                if button.contains_point(mouse_x, mouse_y) {
                    self.handle_button_click(button.action, ctx);
                    return true; // 表示处理了鼠标点击
                }
            }
        }
        false // 表示没有处理鼠标点击
    }

    fn main_menu(&mut self, ctx: &mut BTerm) {
        ctx.cls();
        if self.buttons.is_empty() {
            self.create_menu_buttons();
        }
        // 加粗主标题
        for dy in 0..3 {
            ctx.print_centered(5 + dy, "Welcome to Flappy Birds！");
        }
        ctx.print_centered(10, "Click buttons or use keyboard shortcuts:");
        ctx.print_centered(12, "P - Play, Q - Quit, M - Audio, B - Music");
        self.set_background(ctx, "assets/background.png");
        for button in &self.buttons {
            button.render(ctx);
        }
        let mouse_handled = self.handle_mouse(ctx);
        if !mouse_handled {
            if let Some(key) = ctx.key {
                match key {
                    VirtualKeyCode::P => self.restart(),
                    VirtualKeyCode::Q => ctx.quitting = true,
                    VirtualKeyCode::M => {
                        self.audio_enabled = !self.audio_enabled;
                        self.create_menu_buttons();
                    },
                    VirtualKeyCode::B => {
                        self.music_enabled = !self.music_enabled;
                        self.set_music(self.music_enabled);
                        self.create_menu_buttons();
                    },
                    _ => {}
                }
            }
        }
        if self.showing_record {
            let popup_x = 35;
            let popup_y = 12;
            let popup_w = 50;
            let popup_h = 16;
            for dx in 0..popup_w {
                for dy in 0..popup_h {
                    ctx.set(popup_x + dx, popup_y + dy, BLACK, WHITE, to_cp437(' '));
                }
            }
            // 加粗弹窗标题
            for dy in 0..2 {
                ctx.print_centered_at(popup_x + popup_w/2, popup_y + 2 + dy, "All Mode Records");
            }
            ctx.print_centered_at(popup_x + popup_w/2, popup_y + 5, &format!("Easy Mode: {}", self.record_easy));
            ctx.print_centered_at(popup_x + popup_w/2, popup_y + 7, &format!("Normal Mode: {}", self.record_normal));
            ctx.print_centered_at(popup_x + popup_w/2, popup_y + 9, &format!("Challenge Mode: {}", self.record_challenge));
            ctx.print_centered_at(popup_x + popup_w/2, popup_y + 13, "Click anywhere or press Esc to close");
            if !self.record_popup_just_opened && (ctx.left_click || ctx.key == Some(VirtualKeyCode::Escape)) {
                self.showing_record = false;
            }
            if self.record_popup_just_opened {
                self.record_popup_just_opened = false;
            }
        }
    }

    fn play(&mut self, ctx: &mut BTerm) {
        ctx.cls(); // 清空屏幕，防止菜单内容残留
        self.buttons.clear(); // 确保游玩时没有按钮
        self.set_background(ctx, "assets/background.png");
        // 显示分数、速度、音效、模式
        ctx.print(0, 1, &format!("Score: {}", self.score));
        ctx.print(0, 2, &format!("Speed: {:.1}x", self.game_speed));
        ctx.print(0, 3, &format!("Lives: {}", self.lives));
        ctx.print(0, 4, &format!("Audio: {}  Music: {}", if self.audio_enabled { "ON" } else { "OFF" }, if self.music_enabled { "ON" } else { "OFF" }));
        ctx.print(0, 5, &format!("Mode: {}", if self.is_easy_mode { "Easy" } else if self.is_challenge_mode { "Challenge" } else { "Normal" }));
        // 渲染玩家
        self.player.render(ctx, self.player.x);
        // 渲染boom小球（提前，所有分支都能显示）
        for boom in &self.boom_balls {
            boom.render(ctx, self.player.x);
        }
        for live in &self.live_balls {
            live.render(ctx, self.player.x);
        }
        // 按P键暂停
        if let Some(key) = ctx.key {
            if key == VirtualKeyCode::P {
                self.mode = GameMode::Paused;
                return;
            }
        }
        // 撞击后重生倒计时
        if let Some(timer) = &mut self.respawn_timer {
            *timer -= ctx.frame_time_ms;
            // 渲染障碍物
            for obstacle in &mut self.obstacles {
                obstacle.render(ctx, self.player.x);
            }
            // 渲染小球
            for collectible in &mut self.collectibles {
                collectible.render(ctx, self.player.x);
            }
            // 分数、速度、音效等信息始终渲染
            ctx.print(0, 0, "Press Space to Flap");
            ctx.print(0, 1, &format!("Score: {}", self.score));
            ctx.print(0, 2, &format!("Speed: {:.1}x", self.game_speed));
            ctx.print(0, 3, &format!("Lives: {}", self.lives));
            ctx.print(0, 4, &format!("Audio: {}  Music: {}", if self.audio_enabled { "ON" } else { "OFF" }, if self.music_enabled { "ON" } else { "OFF" }));
            // 右上角爱心命数
            if self.is_easy_mode || self.is_challenge_mode {
                let heart_color = RGB::named(YELLOW);
                let base_x = 120 - 16;
                let base_y = 2;
                for i in 0..self.lives {
                    let x0 = base_x + i * 5;
                    let y0 = base_y;
                    let heart_pattern = [
                        [0,1,1,0],
                        [1,1,1,1],
                        [0,1,1,0],
                        [0,1,1,0],
                    ];
                    for dx in 0..4 {
                        for dy in 0..4 {
                            if heart_pattern[dy][dx] == 1 {
                                let px = x0 + dx as i32;
                                let py = y0 + dy as i32;
                                if px >= 0 && px < 120 && py >= 0 && py < 80 {
                                    ctx.set_bg(px, py, (
                                        heart_color.r as u8,
                                        heart_color.g as u8,
                                        heart_color.b as u8,
                                    ));
                                }
                            }
                        }
                    }
                }
            }
            ctx.print_centered(20, "Ouch! Respawning...");
            if *timer <= 0.0 {
                self.respawn_timer = None;
                // 跳过障碍物
                if let Some(idx) = self.pending_skip_obstacle.take() {
                    let max_x = self.obstacles.iter().map(|o| o.x).max().unwrap_or(0);
                    if let Some(obstacle) = self.obstacles.get_mut(idx) {
                        obstacle.x = max_x + OBSTACLE_INTERVAL;
                    }
                }
            }
            return;
        }

        // 检查是否需要加速（每5分加速一次）
        if self.score >= self.last_speed_increase_score + 5 {
            self.game_speed += 0.2;
            self.last_speed_increase_score = self.score;
        }
        
        // frame_time_ms 记录了每次调用tick所经过的时间
        self.frame_time += ctx.frame_time_ms;
        // 根据游戏速度调整帧率
        let adjusted_frame_duration = FRAME_DURATION / self.game_speed;
        // 向前移动并且重力增加
        if self.frame_time > adjusted_frame_duration {
            self.frame_time = 0.0;
            self.player.gravity_and_move();
        }
        // 空格触发，往上飞
        if let Some(VirtualKeyCode::Space) = ctx.key {
            self.player.flap();
            self.play_sound(SoundEffect::Flap);
        }
        // 音频切换
        if let Some(VirtualKeyCode::M) = ctx.key {
            self.audio_enabled = !self.audio_enabled;
        }
        // 音乐切换
        if let Some(VirtualKeyCode::B) = ctx.key {
            self.music_enabled = !self.music_enabled;
            self.set_music(self.music_enabled);
        }
        // 渲染
        // 简单模式右上角显示命数爱心
        if self.is_easy_mode || self.is_challenge_mode {
            let heart_color = RGB::named(YELLOW);
            let base_x = 120 - 16;
            let base_y = 2;
            for i in 0..self.lives {
                let x0 = base_x + i * 5;
                let y0 = base_y;
                let heart_pattern = [
                    [0,1,1,0],
                    [1,1,1,1],
                    [1,1,1,1],
                    [0,1,1,0],
                ];
                for dx in 0..4 {
                    for dy in 0..4 {
                        if heart_pattern[dy][dx] == 1 {
                            let px = x0 + dx as i32;
                            let py = y0 + dy as i32;
                            if px >= 0 && px < 120 && py >= 0 && py < 80 {
                                ctx.set_bg(px, py, (
                                    heart_color.r as u8,
                                    heart_color.g as u8,
                                    heart_color.b as u8,
                                ));
                            }
                        }
                    }
                }
            }
        }

        // 渲染障碍物
        for obstacle in &mut self.obstacles {
            obstacle.render(ctx, self.player.x);
        }

        // 渲染小球
        for collectible in &mut self.collectibles {
            collectible.render(ctx, self.player.x);
        }

        // 检查是否越过障碍物
        let mut passed = None;
        let mut hit_obstacle = false;
        let mut hit_obstacle_idx = None;
        for (i, obstacle) in self.obstacles.iter_mut().enumerate() {
            if self.player.x > obstacle.x {
                passed = Some(i);
            }
            if obstacle.hit_obstacle(&self.player) {
                hit_obstacle = true;
                hit_obstacle_idx = Some(i);
            }
        }
        
        // 检查小球收集
        let mut collected_count = 0;
        for collectible in &mut self.collectibles {
            if collectible.check_collision(&self.player) {
                collected_count += 1;
            }
        }
        
        // 处理收集的小球
        if collected_count > 0 {
            self.score += collected_count; // 收集小球加1分
            self.play_sound(SoundEffect::Fruit); // 播放收集音效
            // 检查并更新最高分
            if self.is_easy_mode {
                if self.score > self.record_easy {
                    self.record_easy = self.score;
                    let _ = std::fs::write("record_easy.txt", self.record_easy.to_string());
                }
            } else if self.is_challenge_mode {
                if self.score > self.record_challenge {
                    self.record_challenge = self.score;
                    let _ = std::fs::write("record_challenge.txt", self.record_challenge.to_string());
                }
            } else {
                if self.score > self.record_normal {
                    self.record_normal = self.score;
                    let _ = std::fs::write("record_normal.txt", self.record_normal.to_string());
                }
            }
        }
        
        // 简单模式撞障碍物处理、挑战模式撞障碍物处理
        if (self.is_easy_mode && hit_obstacle) || (self.is_challenge_mode && hit_obstacle) {
            if self.lives > 1 {
                self.lives -= 1;
                self.play_sound(SoundEffect::Hit);
                self.respawn_timer = Some(1000.0); // 1秒
                self.pending_skip_obstacle = hit_obstacle_idx;
                self.game_speed = (self.game_speed - 0.2).max(1.0);
                // 重生点在被撞障碍物之后
                if let Some(idx) = hit_obstacle_idx {
                    let obstacle = &self.obstacles[idx];
                    self.player = Player::new(obstacle.x + 6, obstacle.gap_y - 3);
                } else {
                    self.player = Player::new(5, 25);
                }
                return;
            } else {
                self.mode = GameMode::End;
                self.play_sound(SoundEffect::Hit);
                return;
            }
        }
        // 普通模式撞障碍物
        if !self.is_easy_mode && hit_obstacle {
            self.mode = GameMode::End;
            self.play_sound(SoundEffect::Hit);
            return;
        }
        
        // 检查boom小球碰撞
        if self.is_challenge_mode {
            let mut hit_boom = false;
            let mut remove_idx = None;
            for (i, boom) in self.boom_balls.iter().enumerate() {
                if boom.check_collision(&self.player) {
                    hit_boom = true;
                    remove_idx = Some(i);
                    break;
                }
            }
            if let Some(idx) = remove_idx {
                self.boom_balls.remove(idx);
            }
            if hit_boom {
                if self.lives > 1 {
                    self.lives -= 1;
                    self.play_sound(SoundEffect::Hit);
                    self.respawn_timer = Some(1000.0);
                    self.pending_skip_obstacle = None; // 不跳过障碍物
                    self.game_speed = (self.game_speed - 0.2).max(1.0);
                    // 重生点为当前玩家位置
                    self.player = Player::new(self.player.x, self.player.y);
                    return;
                } else {
                    self.mode = GameMode::End;
                    self.play_sound(SoundEffect::Hit);
                    return;
                }
            }
            // live_ball判定
            let mut add_life = false;
            let mut remove_live_idx = None;
            for (i, live) in self.live_balls.iter().enumerate() {
                if live.check_collision(&self.player) {
                    add_life = true;
                    remove_live_idx = Some(i);
                    break;
                }
            }
            if let Some(idx) = remove_live_idx {
                self.live_balls.remove(idx);
            }
            if add_life {
                self.lives += 1;
                self.play_sound(SoundEffect::Fruit); // 可换为新音效
            }
        }

        if let Some(i) = passed {
            self.score += 1;
            // 新障碍物x取当前所有障碍物最大x+OBSTACLE_INTERVAL
            let max_x = self.obstacles.iter().map(|o| o.x).max().unwrap_or(SCREEN_WIDTH);
            let new_x = max_x + OBSTACLE_INTERVAL;
            let new_obstacle = self.create_obstacle_with_constraint(new_x, self.score);
            
            // 为新障碍物生成小球
            self.generate_collectibles(new_x, new_obstacle.gap_y, new_obstacle.size);
            self.try_generate_boom(new_x, new_obstacle.gap_y, new_obstacle.size);
            self.try_generate_live_ball(new_x, new_obstacle.gap_y, new_obstacle.size);
            
            self.obstacles[i] = new_obstacle;
        }

        // 掉出底部直接Game Over
        if self.player.y > SCREEN_HEIGHT {
            self.mode = GameMode::End;
            self.play_sound(SoundEffect::GameOver);
        }
    }

    fn pause(&mut self, ctx: &mut BTerm) {
        ctx.cls();
        self.set_background(ctx, "assets/background.png");
        // 渲染玩家
        self.player.render(ctx, self.player.x);
        // 渲染障碍物
        for obstacle in &mut self.obstacles {
            obstacle.render(ctx, self.player.x);
        }
        // 渲染小球
        for collectible in &mut self.collectibles {
            collectible.render(ctx, self.player.x);
        }
        // 渲染boom小球
        for boom in &self.boom_balls {
            boom.render(ctx, self.player.x);
        }
        for live in &self.live_balls {
            live.render(ctx, self.player.x);
        }
        // 分数、速度、音效等信息始终渲染
        ctx.print(0, 1, &format!("Score: {}", self.score));
        ctx.print(0, 2, &format!("Speed: {:.1}x", self.game_speed));
        ctx.print(0, 3, &format!("Lives: {}", self.lives));
        ctx.print(0, 4, &format!("Audio: {}  Music: {}", if self.audio_enabled { "ON" } else { "OFF" }, if self.music_enabled { "ON" } else { "OFF" }));
        // 右上角爱心命数
        if self.is_easy_mode || self.is_challenge_mode {
            let heart_color = RGB::named(YELLOW);
            let base_x = 120 - 16;
            let base_y = 2;
            for i in 0..self.lives {
                let x0 = base_x + i * 5;
                let y0 = base_y;
                let heart_pattern = [
                    [0,1,1,0],
                    [1,1,1,1],
                    [1,1,1,1],
                    [0,1,1,0],
                ];
                for dx in 0..4 {
                    for dy in 0..4 {
                        if heart_pattern[dy][dx] == 1 {
                            let px = x0 + dx as i32;
                            let py = y0 + dy as i32;
                            if px >= 0 && px < 120 && py >= 0 && py < 80 {
                                ctx.set_bg(px, py, (
                                    heart_color.r as u8,
                                    heart_color.g as u8,
                                    heart_color.b as u8,
                                ));
                            }
                        }
                    }
                }
            }
        }
        // 叠加暂停提示
        ctx.print_centered(20, "Game Paused");
        ctx.print_centered(22, "Press P to Resume");
        if let Some(key) = ctx.key {
            if key == VirtualKeyCode::P {
                self.mode = GameMode::Playing;
            }
        }
    }

    fn dead(&mut self, ctx: &mut BTerm) {
        ctx.cls();
        self.set_background(ctx, "assets/background_end.png");
        if self.buttons.is_empty() {
            self.create_end_buttons();
        }
        // 加粗结束标题
        for dy in 0..2 {
            ctx.print_color_centered(5 + dy, BLACK, WHITE, "You are dead！");
        }
        ctx.print_color_centered(8, BLACK, WHITE, &format!("You earned {} points", self.score));
        // 显示当前模式最高分
        let record = if self.is_easy_mode {
            self.record_easy
        } else if self.is_challenge_mode {
            self.record_challenge
        } else {
            self.record_normal
        };
        ctx.print_color_centered(9, BLACK, WHITE, &format!("Record: {}", record));
        if self.score >= record {
            ctx.print_color_centered(10, BLACK, WHITE, "New Record!");
        }
        ctx.print_color_centered(12, BLACK, WHITE, "Click buttons or use keyboard shortcuts:");
        ctx.print_color_centered(13, BLACK, WHITE, "P - Play Again, Q - Quit, M - Audio, B - Music");
        for button in &self.buttons {
            button.render(ctx);
        }
        let mouse_handled = self.handle_mouse(ctx);
        if !mouse_handled {
            if let Some(key) = ctx.key {
                match key {
                    VirtualKeyCode::P => {
                        if self.handle_button_click(ButtonAction::Restart, ctx) {}
                    },
                    VirtualKeyCode::Q => {
                        if self.handle_button_click(ButtonAction::Quit, ctx) {}
                    },
                    VirtualKeyCode::M => {
                        if self.handle_button_click(ButtonAction::ToggleAudio, ctx) {}
                    },
                    VirtualKeyCode::B => {
                        if self.handle_button_click(ButtonAction::ToggleMusic, ctx) {}
                    },
                    _ => {}
                }
            }
        }
    }

    fn restart(&mut self) {
        self.player = Player::new(5, 25);
        self.frame_time = 0.0;
        self.mode = GameMode::Playing;
        self.obstacles.clear();
        self.collectibles.clear(); // 清空小球列表
        self.last_obstacle_gap_y = None; // 重置障碍物位置跟踪
        self.game_speed = 1.0; // 重置游戏速度
        self.last_speed_increase_score = 0; // 重置加速分数
        self.lives = if self.is_easy_mode || self.is_challenge_mode { 3 } else { 1 }; // 根据模式设置生命数
        self.respawn_timer = None; // 重置重生倒计时
        self.pending_skip_obstacle = None; // 重置跳过障碍物索引
        self.boom_balls.clear(); // 清空boom小球
        self.live_balls.clear(); // 清空live小球
        let mut x = SCREEN_WIDTH;
        for _ in 0..INITIAL_OBSTACLES {
            let obstacle = self.create_obstacle_with_constraint(x, 0);
            self.generate_collectibles(x, obstacle.gap_y, obstacle.size);
            self.obstacles.push(obstacle);
            x += OBSTACLE_INTERVAL;
        }
        self.score = 0;
        self.buttons.clear(); // 清空按钮列表
    }

    pub fn set_background(&mut self, ctx: &mut BTerm, url: &str) {
        let img = image::open(url).unwrap();
        let (img_width, img_height) = img.dimensions();
        
        // 计算缩放比例，让背景图片适应屏幕
        let scale_x = img_width as f32 / SCREEN_WIDTH as f32;
        let scale_y = img_height as f32 / SCREEN_HEIGHT as f32;
        
        // Draw image to console with better scaling
        for x in 0..SCREEN_WIDTH {
            for y in 0..SCREEN_HEIGHT {
                let img_x = (x as f32 * scale_x) as u32;
                let img_y = (y as f32 * scale_y) as u32;
                
                // 确保不超出图片边界
                let img_x = img_x.min(img_width - 1);
                let img_y = img_y.min(img_height - 1);
                
                let pixel = img.get_pixel(img_x, img_y);
                ctx.set_bg(x, y, (pixel[0], pixel[1], pixel[2]));
            }
        }
    }
}

impl GameState for State {
    fn tick(&mut self, ctx: &mut BTerm) {
        match self.mode {
            GameMode::Menu => self.main_menu(ctx),
            GameMode::Playing => self.play(ctx),
            GameMode::Paused => self.pause(ctx), // 新增
            GameMode::End => self.dead(ctx),
        }
    }
}

fn main() -> BError {
    let context = BTermBuilder::simple(SCREEN_WIDTH, SCREEN_HEIGHT)?
        .with_title("Flappy Birds")
        .build()?;
    main_loop(context, State::new())
}